<template>
  <div class="app-container">
    <div class="filter-container">
      <el-row :gutter="18" type="flex">
        <el-col :span="2">
          <el-button icon="el-icon-s-grid" type="primary" @click="handleInit">全部</el-button>
        </el-col>
        <el-col :span="2">
          <el-button icon="el-icon-circle-plus-outline" type="primary" @click="handleAdd">新增</el-button>
        </el-col>
        <el-col :span="6">
          <el-input v-model="filter.author" placeholder="请输入作者" clearable name="author"></el-input>
        </el-col>
        <el-col :span="2">
          <el-button icon="el-icon-search" type="primary" @click="handleFilter">搜索</el-button>
        </el-col>
      </el-row>
    </div>
    <el-table v-loading="listLoading" :data="list" element-loading-text="Loading" border fit
      highlight-current-row>
      <el-table-column align="center" label="ID" width="95">
        <template v-slot="scope">
          {{ scope.row.id }}
        </template>
      </el-table-column>
      <el-table-column label="标题">
        <template v-slot="scope">
          {{ scope.row.title }}
        </template>
      </el-table-column>
      <el-table-column label="作者" width="110" align="center">
        <template v-slot="scope">
          <span>{{ scope.row.author }}</span>
        </template>
      </el-table-column>
      <el-table-column label="页面" width="110" align="center">
        <template v-slot="scope">
          {{ scope.row.pageviews }}
        </template>
      </el-table-column>
      <el-table-column class-name="status-col" label="状态" width="110" align="center">
        <template v-slot="scope">
          <el-tag :type="scope.row.status">{{ propertyFilter(scope.row.status) }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column align="center" prop="created_at" label="创建时间" width="200">
        <template v-slot="scope">
          <i class="el-icon-time" />
          <span>{{ scope.row.display_time }}</span>
        </template>
      </el-table-column>
      <!-- 操作列 -->
      <el-table-column label="操作" align="center">
        <template v-slot="scope">
          <el-button type="primary" icon="el-icon-edit" @click="handleEdit(scope)">更新</el-button>
          <el-button type="danger" icon="el-icon-remove" @click="handleDelete(scope)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <pagination 
      layout="sizes, prev, pager, next" 
      v-show="total > 0" 
      :total="total" 
      v-model:page="listQuery.page"
      v-model:limit="listQuery.limit" 
      @pagination="paginationChange">
    </pagination>
    <!-- 编辑 -->
    <el-dialog :title="dialogType === 'update' ? '编辑': '新增'" v-model="dialogVisible" width="30%">
      <el-form ref="forms" :model="form" :rules="rules" label-width="80px" label-position="left">
        <el-form-item prop="title" label="标题:">
          <el-input v-model="form.title" placeholder="请输入标题"></el-input>
        </el-form-item>
        <el-form-item prop="author" label="作者:">
          <el-input v-model="form.author" placeholder="请输入作者"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="dialogConfirm">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
<script>
  import { toRefs, reactive } from 'vue'
  import { repositoriesList } from './tableModel/index'
  import { deepClone } from '@/utils/index'
  import Pagination from '@/components/Pagination/index.vue'
  const formModel = {
    author: '',
    display_time: '1986-05-22 07:06:58',
    id: 127100,
    pageviews: 518,
    status: 'draft',
    title: ''
  };
  export default {
    components: {
      Pagination
    },
    setup() {
      const { state, form, filter, fetchData, addData, updateData, deleteData } = repositoriesList()
      const rules = reactive({
        // 校验规则
        author: [{ required: true, message: "作者为必填项" }],
        title: [{ required: true, message: "标题为必填项" }],
      });
      return { 
        ...toRefs(state),
        form, // form组件中ref="forms"，ref中暴露出的实例名必须和model绑定的名不同，如果相同，ref直接绑定setup中返回的form值，form就会被改变，导致抛出警告表单验证失败以及无法输入。
        rules,
        filter,
        fetchData,
        addData,
        deleteData
      }
    },
    methods: {
      paginationChange() {
        this.fetchData()
      },
      // 过滤器 vue3中已经移除过滤器，用计算属性替代，或者通过方法调用实现。
      propertyFilter(value) {
        const status = {
          'published': '发布',
          'draft': '编辑',
          'deleted': '删除',
        };
        return status[value];
      },
      // 确认
      dialogConfirm() {
        this.$refs.forms.validate((valid) => {
          if (valid) {
            if (this.dialogType === 'add') {
              this.list.unshift(this.form)
            } else {
              let current = this.list.findIndex(item => {
                return this.form.id === item.id;
              });
              this.list[current] = Object.assign(this.list[current], this.form)
              // this.$set(this.list, current, this.form) this.$set在3.0中仅兼容构建，定义在reactive下的对象是深度响应式的。
            }
            this.dialogVisible = false
          } else {
            console.log('验证失败!!');
            return false;
          }
        });
      },
      // 添加
      handleAdd() {
        this.dialogType = 'add'
        this.dialogVisible = true
        this.form = deepClone(formModel)
      },
      // 更新
      handleEdit({ row, $index }) {
        this.dialogType = 'update'
        this.dialogVisible = true
        this.form = deepClone(row)
        console.log('form', this.form);
      },
      // 删除
      handleDelete({ row, $index }) {
        this.$confirm('确认删除吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(res => {
          this.list.splice($index, 1);
        }).catch(err => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      },
      // 全部
      handleInit() {
        this.fetchData()
      },
      // 搜索
      handleFilter() {
        this.list = this.list.filter(item => {
          return item.author.includes(this.filter.author);
        });
      }
    }
  }
</script>
<style lang="scss" scoped>
  .filter-container {
    margin-bottom: 20px;
  }
</style>
